<script setup>
  import { Plus, Upload } from '@element-plus/icons-vue';
  import { ref } from 'vue';
  import avatar from '@/assets/default.png'
  import {useUserInfoStore} from "@/stores/userInfo.js";
  import {useTokenStore} from '@/stores/token.js'
  import {updateUserAvatarService} from "@/api/user.js";
  import {ElMessage} from "element-plus";

  const uploadRef = ref();
  const userInfoStore = useUserInfoStore();
  const userInfo = ref({...userInfoStore.userInfo});
  const imgUrl = ref(userInfoStore.userInfo.userPic);
  //获取token
  const token = useTokenStore().token;

  //上传成功
  const uploadSuccess = (res) => {
    imgUrl.value = res.data;
  }

  //上传头像
  const updataAvatar = async () => {
    let res = await updateUserAvatarService(imgUrl.value);
    ElMessage.success("修改成功")
    //修改存储在pinia中的用户信息后，userStore会自动更新
    userInfoStore.userInfo.userPic = imgUrl.value;
  }
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>更换头像</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="true"
            action="/api/upload"
            name="file"
            :headers="{'Authorization':token}"
            :on-success="uploadSuccess">
        <img v-if="imgUrl" :src="imgUrl" class="avatar" />
        <img v-else :src="avatar" width="278" />
        </el-upload>
        <br />
        <el-button type="primary" :icon="Plus" size="large" @click="uploadRef.$el.querySelector('input').click()">
          选择图片
        </el-button>
        <el-button type="success" :icon="Upload" size="large" @click="updataAvatar()">
          上传头像
        </el-button>
        </el-col>
    </el-row>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  margin-top: 20px;
}
.header {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}
.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 278px;
  height: 278px;
  border: 1px dashed #d9d9d9;
  cursor: pointer;
}
.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}
</style>
